<template>
  <div class="settings-container">
    <div class="app-container">
      <el-card>
        <!-- 具体页面结构 -->
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height:60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="sAdd"
              >新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table :data="list">
              <el-table-column label="序号" width="120" type="index" />
              <el-table-column label="角色名称" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button
                    size="small"
                    type="success"
                    @click="assign(scope.row.id)"
                  >分配权限</el-button>
                  <el-button
                    size="small"
                    type="primary"
                    @click="sEdit(scope.row.id)"
                  >编辑</el-button>
                  <el-button
                    size="small"
                    type="danger"
                    @click="sDel(scope.row.id)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页组件 -->
            <el-row type="flex" justify="center" align="middle" style="height: 60px">
              <el-pagination
                :current-page="pageForm.page"
                :page-sizes="[2, 3, 5, 10]"
                :page-size="pageForm.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <!-- 角色弹框 -->
      <el-dialog
        :title="isEdit?'编辑角色':'新增角色'"
        :visible.sync="showDialog"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        @close="hclose"
      >
        <el-form ref="formRef" :model="form" :rules="rules">
          <el-form-item label="角色名称" label-width="80px" prop="name">
            <el-input v-model="form.name" autocomplete="off" />
          </el-form-item>
          <el-form-item label="角色描述" label-width="80px">
            <el-input v-model="form.description" autocomplete="off" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="sCandel">取 消</el-button>
          <el-button type="primary" @click="isOk">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 分配权限弹框 -->
      <!-- 分配权限的弹层 -->
      <el-dialog
        title="分配权限(一级为路由页面查看权限-二级为按钮操作权限)"
        :visible.sync="showDialogAssign"
      >
        <assign-permission
          v-if="showDialogAssign"
          :cur-id="curId"
          @close="showDialogAssign=false"
          @success="success"
        />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getSettings, DelSetting, addSetting, getSettingById, updateSettingById } from '@/api/settings'
import assignPermission from './assignPermission.vue'
export default {
  name: 'Settings',
  components: {
    assignPermission
  },
  data() {
    return {
      // 当前id
      curId: 0,
      showDialogAssign: false,
      // 所有角色的列表
      list: [],
      // 总角色数
      total: 0,
      // pageForm
      pageForm: {
        page: 1,
        pagesize: 3
      },
      // 弹框显示
      showDialog: false,
      // 表单信息
      form: {
        name: '',
        description: ''
      },
      // 编辑与否
      isEdit: false,
      // companyId
      companyId: '',
      rules: {
        name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }]
      }
    }
  },
  created() {
    // 刷新页面
    this.setSettings()
  },
  methods: {
    // 获取所有角色列表
    async setSettings() {
      try {
        const res = await getSettings(this.pageForm)
        // console.log(res, '获取所有角色列表')
        this.list = res.data.data.rows
        this.total = res.data.data.total
      } catch (error) {
        console.log(error)
      }
    },
    // 每条几页
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      this.pageForm.pagesize = val
      this.setSettings()
    },
    // 换到了第几页
    handleCurrentChange(page) {
      // console.log(`当前页: ${page}`)
      this.pageForm.page = page
      this.setSettings()
    },
    // 编辑打开弹框
    async sEdit(id) {
      this.showDialog = true
      this.isEdit = true
      try {
        const res = await getSettingById(id)
        // console.log(res)
        this.form = res.data.data
      } catch (error) {
        console.log(error)
      }
    },
    // 删除
    sDel(id) {
      try {
        this.$confirm('确定删除角色吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          await DelSetting(id)
          if (this.list.length === 1) {
            this.pageForm.page--
            if (this.pageForm.page < 1) {
              this.pageForm.page = 1
            }
          }
          this.setSettings()
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      } catch (error) {
        console.log(error)
      }
    },
    // 新增角色按钮
    sAdd() {
      this.showDialog = true
      this.isEdit = false
    },
    // 确定按钮
    isOk() {
      this.$refs.formRef.validate((valid) => {
        if (!valid) return // 如果表单验证不通过，直接return
        // 通过的代码
        this.isEdit ? this.getNewSettingById() : this.doadd()
      })
    },
    // 关闭弹框触发
    hclose() {
      this.form = {
        name: '',
        description: ''
      }
      this.$refs.formRef.resetFields()
      this.setSettings()
    },
    // 取消按钮
    sCandel() {
      this.showDialog = false
    },
    // 更新角色
    async getNewSettingById() {
      try {
        await updateSettingById(this.form)
        // console.log(res)
        this.$message.success('编辑成功')
        this.showDialog = false
      } catch (error) {
        console.log(error)
      }
      // console.log(res)
    },
    // 新增角色函数
    async doadd() {
      try {
        await addSetting(this.form)
        // console.log(res, '新增')
        this.$message.success('新增成功')
        const maxNum = Math.ceil(this.total / this.pageForm.pagesize)
        this.showDialog = false
        if (this.total % this.pageForm.pagesize === 0) {
          this.pageForm.page = maxNum + 1
          this.total++
        } else {
          // 想查看最新添加的数据，要跳到最大页码
          this.pageForm.page = maxNum
        }
      } catch (error) {
        console.log(error)
      }
    },
    // 分配权限
    assign(id) {
      this.showDialogAssign = true
      this.curId = id
    },
    // 成功
    success() {
      this.showDialogAssign = false
      this.setSettings()
    }
  }
}
</script>

<style>

</style>
